<?php

namespace Addons\IntegralShop\Repositor;

use Addons\IntegralShop\Model\IsGoodModel;
use Addons\IntegralShop\Model\IsOrderModel;
use Addons\IntegralShop\Model\IsUserModel;

class IsOrderRepositor extends BaseRepositor
{
    const STATUS_WAIT = 0;
    const STATUS_FANISH = 1;
    const STATUS_REJECT = -1;

    static private $labels = [
        self::STATUS_WAIT => "待处理",
        self::STATUS_FANISH => "已完成",
        self::STATUS_REJECT => "已拒绝"
    ];

    static private $labelsHtml = [
        self::STATUS_WAIT => "待处理",
        self::STATUS_FANISH => "<font color='green'>已完成</font>",
        self::STATUS_REJECT => "<font color='red'>已拒绝</font>"
    ];

    public static function getStatus($status = null)
    {
        if ($status === null) {
            return self::$labels;
        } else {
            return isset(self::$labels[$status]) ? self::$labels[$status] : "";
        }
    }

    public static function getStatusHtml($status = null)
    {
        if ($status === null) {
            return self::$labelsHtml;
        } else {
            return isset(self::$labelsHtml[$status]) ? self::$labelsHtml[$status] : "";
        }
    }

    private $model;

    public function __construct()
    {
        $this->model = new IsOrderModel();
    }

    /**
     * 修改订单状态
     * @param $id
     * @param $status
     * @return bool|int|string
     */
    public function setStauts($id, $status,$errMsg = "")
    {
        return $this->model->where('id', $id)->save([
            "status" => $status,
            "err_msg" => $errMsg,
            "updated_at" => commonTimeFormat()
        ]);
    }

    /**
     * 获取商品订单数
     * @param $goodId
     * @return mixed
     */
    public function getOrderNumByGoodId($goodId)
    {
        return $this->model->where([
            'good_id' => $goodId,
            'status' => ['in', [self::STATUS_WAIT, self::STATUS_FANISH]]
        ])->count();
    }

    /**
     * 添加订单
     * @param $params
     * @return bool
     */
    public function addOrder($params)
    {
        $goodModel = new IsGoodModel();

        // 商品是否存在
        $goodInfo = $goodModel->getOne($params['good_id']);
        if (empty($goodInfo)) {
            $this->errMsg = sprintf("商品:%d 不存在", $params['good_id']);
            return false;
        }

        // 数量是否充足
        if(($goodInfo['number'] - $this->getOrderNumByGoodId($goodInfo['id'])) <= 0){
            $this->errMsg = "当前数量不足";
            return false;
        }

        // 获取用户积分信息
        $userModel = new IsUserModel();
        $userInfo = $userModel->getByOpenid(get_openid());

        // 积分是否充足
        if ($goodInfo['need_mark'] > $userInfo['mark']) {
            $this->errMsg = "积分不足";
            return false;
        }

        // 扣除积分
        if (!$userModel->reduceMark(get_openid(), $userInfo['mark'] - $goodInfo['need_mark'], $userInfo['mark'])) {
            $this->errMsg = "请重试";
            return false;
        }

        // 添加积分操作记录
        $recordRepo = new IsSpreadsRecordRepositor();
        $eventContent = sprintf("兑换商品 %s", $goodInfo['name']);
        $recordRepo->add(get_openid(), IsSpreadsRecordRepositor::EVENT_TYPE_EXCHANGE_GOOD, $eventContent, IsSpreadsRecordRepositor::OP_TYPE_REDUCE, $goodInfo['need_mark']);

        // 添加订单
        $orderModel = new IsOrderModel();
        if (!$orderModel->add([
            'openid' => get_openid(),
            'good_id' => $goodInfo['id'],
            'name' => $params['name'],
            'address_code' => $params['address_code'],
            'address' => $params['address'],
            'phone' => $params['phone'],
            'need_mark' => $goodInfo['need_mark'],
            'status' => self::STATUS_WAIT,
            'mpid' => get_mpid(),
            'created_at' => commonTimeFormat(),
            'updated_at' => commonTimeFormat(),
        ])) {
            $this->errMsg = "服务器错误";
            return false;
        }

        return true;
    }

    /**
     * 获取用户订单列表
     * @return mixed
     */
    public function userOrderlist()
    {
        $list = $this->model->where([
            'openid' => get_openid()
        ])->order('id desc')->select();

        $goodModel = new IsGoodModel();

        foreach ($list as &$item){
            $item['goodInfo'] = $goodModel->getOneAllStatus($item['good_id'],['name','cover','price']);
        }

        return $list;
    }

    public function rejectOrder($id,$errMsg){
        $orderInfo = $this->model->getOne($id);
        if(empty($orderInfo)){
            $this->errMsg = "订单不存在";
            return false;
        }

        if($orderInfo['status'] != self::STATUS_WAIT){
            $this->errMsg = "订单已处理";
            return false;
        }

        // 修改订单状态
        if(!$this->setStauts($id,IsOrderRepositor::STATUS_REJECT,$errMsg)){
            $this->errMsg = "服务器错误";
            return false;
        }

        // 返还积分
        $userRepo = new IsUserRepositor();
        while (!$userRepo->updateUserMark($orderInfo['openid'],$orderInfo['need_mark'])){};

        // 添加积分日志
        $recordRepo = new IsSpreadsRecordRepositor();
        $eventContent = "返回积分";
        $recordRepo->add($orderInfo['openid'], IsSpreadsRecordRepositor::EVENT_TYPE_RETURN, $eventContent, IsSpreadsRecordRepositor::OP_TYPE_ADD, $orderInfo['need_mark']);
        return true;
    }
}
